package com.example.service;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import okhttp3.*;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.util.Base64;


@Service
public class SttService
{
    private String theToken;
    public String m2t(MultipartFile file,String filePath,String suffixName)
    {
        String s="";
        theToken=getToken();
        JsonObject jsonObject = new Gson().fromJson(theToken, JsonObject.class);
        theToken= String.valueOf(jsonObject.get("access_token")).replace('\"',' ').trim();
        /**文件所占字节数*/
        long theFileSize = file.getSize();
        try {
            /**获得文件的base64编码*/
            s = Base64.getEncoder().encodeToString(file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        /**构造json*/
        String jsonString = "{\"format\":\""+suffixName+"\",\"rate\":16000,\"dev_pid\":80001,\"channel\":1,\"token\":\""+theToken+"\",\"cuid\":\"baidu_workshop\",\"len\":"+theFileSize+",\"speech\":\""+s+"\"}";
        JsonObject endData=new Gson().fromJson(getReturn(jsonString), JsonObject.class);
        String endTxt=String.valueOf(endData.get("result")).replace('\"',' ').trim();
        return endTxt.substring(1,endTxt.length()-1).trim();
    }
    /**获取用来请求的token*/
    public String getToken()
    {
        String endData="";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=H3dGuXCavn0z5lUJOwsMY5wr&client_secret=rOw0N6KGzpQXVRznYxHRH9h2TzBRm6gS")
                .build();
        try (Response response = client.newCall(request).execute())
        {
            endData=response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return endData;
    }
    public String getReturn(String json)
    {
        String endData = "";
        OkHttpClient client = new OkHttpClient();

        // 设置JSON的MediaType
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");

        // 创建RequestBody
        RequestBody body = RequestBody.create(json, JSON);

        // 构建Request
        Request request = new Request.Builder()
                .url("https://vop.baidu.com/pro_api")
                .post(body) // 设置POST请求体
                .addHeader("Content-Type", "application/json") // 可选，因为RequestBody已经设置了MediaType
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            // 获取响应体并返回
            endData = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return endData;
    }
}
